package com.jltx.xq.simplewatch.widget;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jltxseo
 *         Created by junlintianxia on 2017/08/27.
 */

public class LoadingFlashView extends LinearLayout{

    private List<View> viewList;
    private AnimatorSet mAnimatorSet;

    public LoadingFlashView(Context context) {
        super(context);
        initView();
    }

    public LoadingFlashView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public LoadingFlashView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView(){
        viewList = new ArrayList<>();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        int childCount = getChildCount();
        for (int i=0; i < childCount; i++){
            View child = getChildAt(i);
            viewList.add(child);
        }
        showLoading();
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
        if (visibility == VISIBLE){
            showLoading();
        }else {
            hideLoading();
        }

    }

    public void hideLoading() {
        if (mAnimatorSet == null)
            return;
        if ((!mAnimatorSet.isRunning()) && (!mAnimatorSet.isStarted()))
            return;
        mAnimatorSet.removeAllListeners();
        mAnimatorSet.cancel();
        mAnimatorSet.end();
    }

    public void showLoading(){
        if (getVisibility() != View.VISIBLE) return;
        if (mAnimatorSet == null)
            initAnimation();
        if (mAnimatorSet.isRunning() || mAnimatorSet.isStarted()) return;
        mAnimatorSet.start();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        showLoading();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        hideLoading();
    }

    private void initAnimation() {
        mAnimatorSet = new AnimatorSet();
        List<Animator> animatorList = new ArrayList<>();
        for (int i = 0; i < viewList.size(); i++) {
            ObjectAnimator loadAnimator = ObjectAnimator.ofFloat(viewList.get(i), "alpha", new float[]{1.0F, 0.5F}).setDuration(500L);
            loadAnimator.setStartDelay(100 * i);
            loadAnimator.setRepeatMode(ObjectAnimator.REVERSE);
            loadAnimator.setRepeatCount(-1);
            animatorList.add(loadAnimator);
        }
        mAnimatorSet.playTogether(animatorList);
    }


}
